// JavaScript Document
define(function (require, exports, module) {
	//var Form=require("Form");
	var Utils=require("Utils");
	var Verifier=function(){}
	Verifier.validate=function(rules,data,context,tipsPrefix){
		var inputElement=null;
		var requiredStr="";
		
		//console.log(data);
		if(typeof(tipsPrefix)=="undefined"){
			tipsPrefix="";
		}
		var success,rule,name,value,pattern,required,regExp,tips,validateTips;
		tips="";
		success=true;
		required=false;
		var focusElement=null;
		var maxLength=0;
		var maxRealLength=0;
		
		for(var i in rules){
			rule=rules[i]
			name=i
			pattern=rule.pattern
			required=rule.required
			requiredStr="";
			
			if(typeof rule.length!="undefined"){
				maxLength=rule.length
			}else{
				maxLength=0;
			}
			
			
			if(typeof rule.realLength!="undefined"){
				maxRealLength=rule.realLength
			}else{
				maxRealLength=0;
			}
			
			
			value=data[name]
			
			
			inputElement=document.getElementsByName(name)[0];
			
			
			
			$("[name="+name+"]",context).removeClass("invalid")
			
			if(required==true){
				if(value=="" || typeof(value)=="undefined"){
					success=false
					requiredStr=Utils.getRequiredStr(inputElement,rule);
					var a=rule.title?" 要求：":" ";
					tips+=tipsPrefix+rule.label+" "+requiredStr+a+rule.title+"\n"
					$("[name="+name+"]",context).addClass("invalid")
					if(focusElement==null){
						focusElement=$("[name="+name+"]",context).get(0);
					}
					continue;
				}
			}
			if(value!=""){
				if(pattern!=""){
					regExp=new RegExp(pattern,"g");
					if(!regExp.test(value)){
						success=false
						tips+="\""+tipsPrefix+rule.label+"\" "+requiredStr+" 要求："+rule.title+"\n"
						$("[name="+name+"]",context).addClass("invalid")
						if(focusElement==null){
							focusElement=$("[name="+name+"]",context).get(0);
							$(focusElement).addClass("invalid")
						}
					}else{
						var valueLenght=Utils.encodeXss(value).length;
						if(maxLength>0 && maxLength<valueLenght){
							success=false
							tips+=tipsPrefix+rule.label+" 不能超过 "+maxLength+"字符长度\n"
							$("[name="+name+"]",context).addClass("invalid")
							if(focusElement==null){
								focusElement=$("[name="+name+"]",context).get(0);
								$(focusElement).addClass("invalid")
							}
						}else{
							if(maxRealLength>0){
								var valueRealLength=Utils.getRealLength(value);
								if(maxRealLength<valueRealLength){
									success=false
									tips+=tipsPrefix+rule.label+" 不能超过 "+maxRealLength+"字符长度\n"
									$("[name="+name+"]",context).addClass("invalid")
									if(focusElement==null){
										focusElement=$("[name="+name+"]",context).get(0);
										$(focusElement).addClass("invalid")
									}
								}
							}
						}
					};
				}
			}
			
		}
		if(focusElement!=null){
			if(!$(focusElement).is(":hidden")){
				focusElement.focus()
			}
		}
		if(success==false){
			alert(tips);
		}
		return success;
	}
	
	
	module.exports = Verifier;
});